#!/bin/bash
################################################################################
# Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The OpenAirInterface Software Alliance licenses this file to You under 
# the Apache License, Version 2.0  (the "License"); you may not use this file
# except in compliance with the License.  
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#-------------------------------------------------------------------------------
# For more information about the OpenAirInterface (OAI) Software Alliance:
#      contact@openairinterface.org
################################################################################

# file hss_db_import
# brief   create a database if it does not exist and populate it this provided SQL file
# author Lionel Gauthier
# company Eurecom
# email: lionel.gauthier@eurecom.fr
################################
# include helper functions
################################
THIS_SCRIPT_PATH=$(dirname $(readlink -f $0))
. $THIS_SCRIPT_PATH/../build/tools/build_helper


# arg 1 is mysql hostname  (ex: 127.0.0.1)
# arg 2 is hss username    (ex: hssadmin)
# arg 3 is hss password    (ex: admin)
# arg 4 is database name   (ex: oai_db)
# arg 5 is import file name(ex: oai_db_dump.sql)
function main(){
  EXPECTED_ARGS=5
  if [ $# -ne $EXPECTED_ARGS ]
  then
    echo_error "Usage: hss_db_import mysql_hostname hssuser hsspass databasename filename"
    return 1
  fi
  local mysql_hostname=$1
  local hss_username=$2
  local hss_password=$3
  local database_name=$4
  local file_name=$5
  
  mysqladmin --force -h $mysql_hostname -u $hss_username -p$hss_password drop $database_name 
  
  Q1="CREATE DATABASE IF NOT EXISTS $database_name;"
  mysql -h $mysql_hostname -u $hss_username --password=$hss_password -e "${Q1}"
  if [ $? -ne 0 ]; then
    echo_error "HSS: $database_name creation failed"
    return 1
  else
    echo_success "HSS: $database_name creation succeeded"
  fi
  
  mysql -h $mysql_hostname -u $hss_username -p$hss_password $database_name < $file_name 
  if [ $? -ne 0 ]; then
    echo_error "HSS: $database_name import failed:"
    cat $file_name
    return 1
  else
    echo_success "HSS: $database_name import succeeded"
  fi

  return 0
}

set_openair_env 

main "$@" 

